package com.sangfor.bugreport.logger;

import android.app.ActivityManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Environment;
import android.os.Process;
import android.text.TextUtils;
import androidx.core.os.EnvironmentCompat;
import com.sangfor.ssl.service.https.FileInfo;
import com.sangfor.ssl.service.https.HttpRequest;
import com.sangfor.ssl.service.https.SFException;
import com.sangfor.ssl.service.setting.SettingManager;
import com.sangfor.ssl.service.setting.SystemConfiguration;
import com.sangfor.ssl.service.utils.IGeneral;
import com.sangfor.ssl.service.utils.IOUtils;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.StringWriter;
import java.lang.Thread;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.codehaus.jackson.util.MinimalPrettyPrinter;
import org.json.JSONObject;

/* loaded from: classes2.dex */
public class Log {
    static final /* synthetic */ boolean $assertionsDisabled = false;
    private static final String ACTION_UPDATE_LOG_LEVEL = "com.sangfor.logger.action.UpdateLevel";
    public static final String ALLPROCESS_LOG_ROOT_DIR = "/sangfor/sdklog/";
    public static final String CRASH_LOG_DIR = "/crash/";
    public static final int DEBUG = 3;
    private static final String DEVICE_INFO_FILE_NAME = "deviceinfo.txt";
    public static final int ERROR = 6;
    public static final int FATAL = 7;
    public static final int INFO = 4;
    private static String LINE_SEPARATOR = "\n";
    public static final String LOG_DEBUG_STR = "DEBUG";
    public static final String LOG_ERROR_FATAL = "FATAL";
    public static final String LOG_ERROR_STR = "ERROR";
    public static final String LOG_INFO_STR = "INFO";
    public static final String LOG_VERBOS_STR = "VERBOS";
    public static final String LOG_WARN_STR = "WARN";
    private static final int MAX_CRASH_FILE_LENGTH = 25600;
    private static final long MAX_FILE_LENGTH = 5242880;
    private static final int MAX_JAVA_CRASH_FILES = 10;
    private static final int MAX_LOGCAT_LENGTH = 262144;
    private static final int MAX_NATIVE_CRASH_FILES = 5;
    public static final String NOTIFY_LOG_LEVEL = "Log.Notify.Level";
    private static final String PREF_LOG_LEVEL = "Log.Last.Level";
    private static final String PREF_SHARED_LOG = "Log.Level";
    private static final String PREF_WRITE_LOG_LEVEL = "Log.Last.Write.Level";
    public static final String PROCESS_LOG_DIR = "/process/";
    private static final String TAG = "Log";
    private static final String URL_EASYAPP_REPORT = "http://update1.sangfor.net/sslupdate/easyapp_report.php";
    public static final int VERBOSE = 2;
    private static final String VPN_FLUX_FILE_NAME = "vpnflux.txt";
    private static final String VPN_INFO_FILE_NAME = "vpninfo.txt";
    public static final int WARN = 5;
    private static final String ZIP_LOG_NAME = "SFSDK_ANDROID_%s.log.zip";
    private static String mPackageName = null;
    private static int mPrintLogLevel = 4;
    private static String mProcessName = null;
    private static int mProcessPid = -1;
    private static int mWriteLogLevel = 2;
    private static SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
    private static SimpleDateFormat mDateFormatForFileName = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.CHINA);
    private static String mProcessLogDir = null;
    private static String mCrashLogDir = null;
    private static String mLogRootDir = null;
    private static boolean mIsInit = false;
    private static Thread.UncaughtExceptionHandler mOriHandler = null;

    /* JADX INFO: Access modifiers changed from: private */
    public static native void flushLog();

    private static native boolean initLogFile(String str, int i);

    private static native boolean initVpnFluxFile(String str, String str2);

    private static native boolean initVpnInfoFile(String str);

    private static native void nWriteVpnInfo(String str, String str2);

    private static native void nativeLog(int i, String str, String str2);

    private static native void setLogLevel(int i);

    private static native void setWriteFileLevel(int i);

    public static String getmProcessName() {
        return mProcessName;
    }

    /* loaded from: classes2.dex */
    private static class CrashHandler implements Thread.UncaughtExceptionHandler {
        static final /* synthetic */ boolean $assertionsDisabled = false;

        private CrashHandler() {
        }

        /* JADX WARN: Removed duplicated region for block: B:31:0x00fa A[Catch: IOException -> 0x0115, TRY_ENTER, TRY_LEAVE, TryCatch #2 {IOException -> 0x0115, blocks: (B:38:0x0111, B:31:0x00fa), top: B:53:0x002f }] */
        /* JADX WARN: Removed duplicated region for block: B:61:? A[RETURN, SYNTHETIC] */
        @Override // java.lang.Thread.UncaughtExceptionHandler
        /*
            Code decompiled incorrectly, please refer to instructions dump.
            To view partially-correct code enable 'Show inconsistent code' option in preferences
        */
        public void uncaughtException(java.lang.Thread r11, java.lang.Throwable r12) {
            /*
                Method dump skipped, instructions count: 293
                To view this dump change 'Code comments level' option to 'DEBUG'
            */
            throw new UnsupportedOperationException("Method not decompiled: com.sangfor.bugreport.logger.Log.CrashHandler.uncaughtException(java.lang.Thread, java.lang.Throwable):void");
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static void execOriginalCrashHandler(Thread thread, Throwable th) {
        Thread.UncaughtExceptionHandler uncaughtExceptionHandler = mOriHandler;
        if (uncaughtExceptionHandler != null) {
            uncaughtExceptionHandler.uncaughtException(thread, th);
        }
    }

    public static boolean createDir(String str) {
        info(TAG, "createdir path:" + str);
        File file = new File(str);
        try {
            if (!file.exists()) {
                error(TAG, "file " + str + " not exist.");
                boolean mkdirs = file.mkdirs();
                if (!mkdirs) {
                    error(TAG, "mkdirs %s failed.", str);
                }
                return mkdirs;
            } else if (file.isDirectory()) {
                return true;
            } else {
                error(TAG, "file already exist.but not directory.");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void init(Context context) {
        if (mIsInit) {
            return;
        }
        mProcessPid = Process.myPid();
        mProcessName = getProcessName(context);
        mPackageName = context.getPackageName();
        Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        if (defaultUncaughtExceptionHandler != null && !(defaultUncaughtExceptionHandler instanceof CrashHandler)) {
            mOriHandler = defaultUncaughtExceptionHandler;
            info(TAG, "handler:" + defaultUncaughtExceptionHandler + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + defaultUncaughtExceptionHandler.getClass().getName());
            Thread.setDefaultUncaughtExceptionHandler(new CrashHandler());
        }
        LINE_SEPARATOR = System.getProperty("line.separator");
        if (!Environment.getExternalStorageState().equals("mounted")) {
            error(TAG, "no sdcard.");
            return;
        }
        try {
            String replace = mProcessName.replace(':', '-');
            String absolutePath = Environment.getExternalStorageDirectory().getAbsolutePath();
            mLogRootDir = absolutePath + ALLPROCESS_LOG_ROOT_DIR + mPackageName;
            mProcessLogDir = mLogRootDir + PROCESS_LOG_DIR;
            mCrashLogDir = mLogRootDir + CRASH_LOG_DIR;
            createDir(mProcessLogDir);
            createDir(mCrashLogDir);
            String replace2 = (mProcessLogDir + replace + ".log").replace(':', '_');
            mPrintLogLevel = getLogLevel(context);
            mWriteLogLevel = getWriteLogLevel(context);
            initLogFile(replace2, 0);
            initVpnFluxFile(absolutePath + ALLPROCESS_LOG_ROOT_DIR + VPN_FLUX_FILE_NAME, mPackageName);
            initVpnInfoFile(absolutePath + ALLPROCESS_LOG_ROOT_DIR + VPN_INFO_FILE_NAME);
            setLogLevel(mPrintLogLevel);
            setWriteFileLevel(mWriteLogLevel);
            deleteExtraCrashLog();
            deleteExtraCrashDmp();
            saveDeviceInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        info(TAG, "log init finish");
        mIsInit = true;
    }

    public static void uploadLogDelay(final int i) {
        info(TAG, "upload log delay", "enter");
        new Thread(new Runnable() { // from class: com.sangfor.bugreport.logger.Log.1
            @Override // java.lang.Runnable
            public void run() {
                try {
                    Log.info("upload log delay", "sec = " + i);
                    Thread.sleep((long) (i * 1000));
                    Log.uploadLogsToSangfor(null);
                } catch (Exception unused) {
                }
            }
        }).start();
    }

    private static void saveDeviceInfo() {
        File file = new File(mProcessLogDir + DEVICE_INFO_FILE_NAME);
        if (file.exists()) {
            return;
        }
        FileOutputStream fileOutputStream = null;
        try {
            try {
                FileOutputStream fileOutputStream2 = new FileOutputStream(file);
                try {
                    fileOutputStream2.write(getDeviceInfo().getBytes());
                    closeOutputStream(fileOutputStream2);
                } catch (IOException e) {
                    e = e;
                    fileOutputStream = fileOutputStream2;
                    e.printStackTrace();
                    closeOutputStream(fileOutputStream);
                } catch (Throwable th) {
                    th = th;
                    fileOutputStream = fileOutputStream2;
                    closeOutputStream(fileOutputStream);
                    throw th;
                }
            } catch (IOException e2) {
                e = e2;
            }
        } catch (Throwable th2) {
            th = th2;
        }
    }

    public static void saveVpnInfo(String str, String str2) {
        nWriteVpnInfo(str, str2);
    }

    private static void checkInitStatus() throws Exception {
        if (!mIsInit) {
            throw new IllegalStateException("The Log must be init first.");
        }
    }

    public static String getTunInfo() {
        String str = "";
        try {
            Process exec = Runtime.getRuntime().exec("ip route get 1.1.1.1");
            InputStream inputStream = exec.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            while (true) {
                String readLine = bufferedReader.readLine();
                if (readLine == null) {
                    break;
                }
                str = str + readLine + "\n";
            }
            exec.waitFor();
            inputStream.close();
            bufferedReader.close();
            exec.destroy();
        } catch (Exception e) {
            error(TAG, "writeLogcat failed.", e);
        }
        try {
            Process exec2 = Runtime.getRuntime().exec("ip addr");
            InputStream inputStream2 = exec2.getInputStream();
            BufferedReader bufferedReader2 = new BufferedReader(new InputStreamReader(inputStream2));
            while (true) {
                String readLine2 = bufferedReader2.readLine();
                if (readLine2 == null) {
                    break;
                }
                str = str + readLine2 + "\n";
            }
            exec2.waitFor();
            inputStream2.close();
            bufferedReader2.close();
            exec2.destroy();
        } catch (Exception e2) {
            error(TAG, "writeLogcat failed.", e2);
        }
        info(TAG, "writeTunInfo result = ." + str);
        return str;
    }

    /* JADX WARN: Multi-variable type inference failed */
    /* JADX WARN: Type inference failed for: r4v0, types: [java.io.OutputStream, java.io.FileOutputStream] */
    public static String packLogs(String str) throws Exception {
        ZipOutputStream zipOutputStream;
        ZipOutputStream zipOutputStream2;
        checkInitStatus();
        if (TextUtils.isEmpty(str)) {
            str = mLogRootDir + File.separatorChar + String.format(ZIP_LOG_NAME, "1");
        }
        if (!Environment.getExternalStorageState().equals("mounted")) {
            return "";
        }
        String str2 = mLogRootDir;
        ZipOutputStream zipOutputStream3 = null;
        try {
            synchronized (Log.class) {
                try {
                    ?? fileOutputStream = new FileOutputStream(str, false);
                    try {
                        zipOutputStream2 = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
                    } catch (Throwable th) {
                        th = th;
                        zipOutputStream2 = null;
                    }
                    try {
                        flushLog();
                        zipFile(zipOutputStream2, new File(mCrashLogDir), "");
                        zipFile(zipOutputStream2, new File(mProcessLogDir), "");
                        String str3 = str2 + "/logcat.log";
                        writeLogcat(str3);
                        zipFile(zipOutputStream2, new File(str3), "");
                        String deviceInfo = getDeviceInfo();
                        if (deviceInfo != null) {
                            zipOutputStream2.putNextEntry(new ZipEntry("DeviceInfo.log"));
                            zipOutputStream2.write(deviceInfo.getBytes());
                            zipOutputStream2.flush();
                            zipOutputStream2.closeEntry();
                        }
                        String tunInfo = getTunInfo();
                        if (tunInfo != null) {
                            zipOutputStream2.putNextEntry(new ZipEntry("TunInfo.log"));
                            zipOutputStream2.write(tunInfo.getBytes());
                            zipOutputStream2.flush();
                            zipOutputStream2.closeEntry();
                        }
                        closeZipStream(zipOutputStream2);
                        closeOutputStream(fileOutputStream);
                        return str;
                    } catch (Throwable th2) {
                        th = th2;
                        zipOutputStream3 = fileOutputStream;
                        while (true) {
                            try {
                                try {
                                    try {
                                        break;
                                    } catch (Throwable th3) {
                                        th = th3;
                                        zipOutputStream = zipOutputStream3;
                                        zipOutputStream3 = zipOutputStream2;
                                        closeZipStream(zipOutputStream3);
                                        closeOutputStream(zipOutputStream);
                                        throw th;
                                    }
                                } catch (IOException e) {
                                    e = e;
                                    error(TAG, "Unable to pack logs", e);
                                    throw e;
                                }
                            } catch (Throwable th4) {
                                th = th4;
                            }
                        }
                        throw th;
                    }
                } catch (Throwable th5) {
                    th = th5;
                    zipOutputStream2 = null;
                }
            }
        } catch (IOException e2) {
            e = e2;
            zipOutputStream2 = null;
        } catch (Throwable th6) {
            th = th6;
            zipOutputStream = null;
            closeZipStream(zipOutputStream3);
            closeOutputStream(zipOutputStream);
            throw th;
        }
    }

    public static String uploadLogsToSangfor(String str) throws Exception {
        String packLogs = packLogs(null);
        if (TextUtils.isEmpty(packLogs)) {
            throw new IOException("pack log error.");
        }
        info(TAG, "start upLoad to bug report");
        File file = new File(packLogs);
        if (str == null) {
            str = URL_EASYAPP_REPORT;
        }
        String sendFile = sendFile(str, file);
        if (TextUtils.isEmpty(sendFile)) {
            error(TAG, "uploadLog failed.");
            throw new Exception("uploadLog failed.");
        }
        info(TAG, "upload bug report result:" + sendFile);
        try {
            JSONObject jSONObject = new JSONObject(sendFile.substring(sendFile.indexOf("{"), sendFile.lastIndexOf("}") + 1));
            if (TextUtils.equals(jSONObject.getString("result"), "success")) {
                return jSONObject.getLong("issue_id") + "$" + file;
            }
        } catch (Exception e) {
            error(TAG, "upload error. %s ", sendFile, e);
        }
        throw new Exception("uploadLog failed." + sendFile);
    }

    private static String sendFile(String str, File file) throws Exception {
        String str2 = (String) SettingManager.getInstance().get(SettingManager.SETTING_USERNAME, EnvironmentCompat.MEDIA_UNKNOWN);
        String vpnHost = SystemConfiguration.getInstance().getVpnHost();
        String str3 = Build.MODEL;
        HttpRequest httpRequest = null;
        try {
            try {
                HashMap hashMap = new HashMap();
                hashMap.put("user", str2);
                hashMap.put("vpn", vpnHost);
                hashMap.put("mobile", str3 + "_0");
                httpRequest = HttpRequest.post(str, hashMap);
                FileInfo fileInfo = new FileInfo(file);
                fileInfo.setFileBoundary("file");
                httpRequest.setPostFile(fileInfo);
                httpRequest.setRequestHeader(IGeneral.HTTP_HEAD_CHARSET, com.sangfor.kevinsawicki.http.HttpRequest.ENCODING_GZIP);
                httpRequest.setConnectTimeout(10);
                return httpRequest.getResponse();
            } catch (SFException e) {
                error(TAG, "upLoad to bug report error.", e);
                throw e;
            }
        } finally {
            IOUtils.closeQuietly(httpRequest);
        }
    }

    private static void closeOutputStream(OutputStream outputStream) {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void closeZipStream(ZipOutputStream zipOutputStream) {
        if (zipOutputStream != null) {
            try {
                zipOutputStream.finish();
                zipOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /* JADX WARN: Multi-variable type inference failed */
    /* JADX WARN: Type inference failed for: r3v1, types: [java.io.OutputStream, java.io.FileOutputStream] */
    public static void zipLogs(File file) throws Exception {
        ZipOutputStream zipOutputStream;
        ZipOutputStream zipOutputStream2;
        ?? fileOutputStream;
        checkInitStatus();
        if (Environment.getExternalStorageState().equals("mounted")) {
            String str = mProcessLogDir;
            ZipOutputStream zipOutputStream3 = null;
            try {
                synchronized (Log.class) {
                    try {
                        fileOutputStream = new FileOutputStream(file, false);
                        try {
                            zipOutputStream2 = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
                        } catch (Throwable th) {
                            th = th;
                            zipOutputStream2 = null;
                        }
                    } catch (Throwable th2) {
                        th = th2;
                        zipOutputStream2 = null;
                    }
                    try {
                        File file2 = new File(mCrashLogDir);
                        if (file2.exists()) {
                            zipFile(zipOutputStream2, file2, "");
                        }
                        String str2 = str + "/logcat.log";
                        if (!writeLogcat(str2)) {
                            copyProcessInfo2Logcat(str2);
                        }
                        cropFileSize(str, "logcat.log", 262144);
                        zipFile(zipOutputStream2, new File(str2), "");
                        String deviceInfo = getDeviceInfo();
                        if (deviceInfo != null) {
                            zipOutputStream2.putNextEntry(new ZipEntry("DeviceInfo.log"));
                            zipOutputStream2.write(deviceInfo.getBytes());
                            zipOutputStream2.flush();
                            zipOutputStream2.closeEntry();
                        }
                        closeZipStream(zipOutputStream2);
                        closeOutputStream(fileOutputStream);
                        return;
                    } catch (Throwable th3) {
                        th = th3;
                        zipOutputStream3 = fileOutputStream;
                        while (true) {
                            try {
                                break;
                            } catch (Throwable th4) {
                                th = th4;
                            }
                        }
                        throw th;
                    }
                }
            } catch (IOException e) {
                e = e;
                zipOutputStream = null;
            } catch (Throwable th5) {
                th = th5;
                zipOutputStream = null;
            }
            try {
                break;
                throw th;
            } catch (IOException e2) {
                e = e2;
                ZipOutputStream zipOutputStream4 = zipOutputStream3;
                zipOutputStream3 = zipOutputStream2;
                zipOutputStream = zipOutputStream4;
                try {
                    error(TAG, "Unable to get device info.", e);
                    closeZipStream(zipOutputStream3);
                    closeOutputStream(zipOutputStream);
                } catch (Throwable th6) {
                    th = th6;
                    closeZipStream(zipOutputStream3);
                    closeOutputStream(zipOutputStream);
                    throw th;
                }
            } catch (Throwable th7) {
                th = th7;
                ZipOutputStream zipOutputStream5 = zipOutputStream3;
                zipOutputStream3 = zipOutputStream2;
                zipOutputStream = zipOutputStream5;
                closeZipStream(zipOutputStream3);
                closeOutputStream(zipOutputStream);
                throw th;
            }
        }
    }

    private static void copyProcessInfo2Logcat(String str) throws Exception {
        checkInitStatus();
        File[] listFiles = new File(mProcessLogDir).listFiles();
        if (listFiles == null || listFiles.length <= 0) {
            return;
        }
        for (File file : listFiles) {
            if (file.exists() && !file.isDirectory()) {
                copyContentFile2File(str, file, 262144 / listFiles.length);
            }
        }
    }

    private static void copyContentFile2File(String str, File file, int i) {
        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile(file.getAbsolutePath(), "r");
            long length = randomAccessFile.length() - i;
            if (length < 0) {
                length = 0;
            }
            randomAccessFile.seek(length);
            byte[] bArr = new byte[1024];
            FileOutputStream fileOutputStream = new FileOutputStream(str, true);
            fileOutputStream.write(("\r\n" + file.getName() + "\r\n").getBytes());
            while (true) {
                int read = randomAccessFile.read(bArr);
                if (read != -1) {
                    fileOutputStream.write(bArr, 0, read);
                } else {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    randomAccessFile.close();
                    return;
                }
            }
        } catch (Exception e) {
            error(TAG, "readUpdateContentFromFile failed. ", e);
        }
    }

    private static void deleteExtraCrashLogOrDmp(String str, String str2, int i) {
        if (TextUtils.isEmpty(str) || TextUtils.isEmpty(str2)) {
            error(TAG, "args is null.");
            return;
        }
        File file = new File(mCrashLogDir);
        if (file.isDirectory()) {
            String[] list = file.list();
            if (list == null || list.length < 1) {
                info(TAG, "filenames is empty.");
                return;
            }
            ArrayList arrayList = new ArrayList();
            for (String str3 : list) {
                if (str3.startsWith(str) && str3.endsWith(str2)) {
                    arrayList.add(str3);
                }
            }
            info(TAG, str2 + " file list size:" + arrayList.size());
            if (arrayList.size() > i) {
                Collections.sort(arrayList, new Comparator<String>() { // from class: com.sangfor.bugreport.logger.Log.2
                    @Override // java.util.Comparator
                    public int compare(String str4, String str5) {
                        return str4.compareTo(str5);
                    }
                });
                int size = arrayList.size() - i;
                info(TAG, "clear " + size + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + str2 + " file.");
                for (int i2 = 0; i2 < size; i2++) {
                    try {
                        Runtime.getRuntime().exec(new String[]{"rm", mCrashLogDir + ((String) arrayList.get(i2))});
                    } catch (IOException e) {
                        error(TAG, "delete " + str2 + " file failed.", e);
                    }
                }
            }
        }
    }

    private static void deleteExtraCrashLog() {
        String replace = mProcessName.replace(':', '-');
        deleteExtraCrashLogOrDmp("crash-" + replace + "--", ".log", 10);
    }

    private static void deleteExtraCrashDmp() {
        String replace = mProcessName.replace(':', '-');
        deleteExtraCrashLogOrDmp("crash-" + replace + "--", ".dmp", 5);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static boolean writeCrashLog(String str, String str2) {
        return writeLogcat(str + "/" + str2);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static void cropFileSize(String str, String str2, int i) throws IOException {
        String str3 = str + "/" + str2;
        File file = new File(str3);
        long j = i;
        if (file.length() <= j) {
            return;
        }
        String str4 = str + "/tmp_" + System.currentTimeMillis();
        File file2 = new File(str4);
        file.renameTo(file2);
        File file3 = new File(str3);
        if (!file3.exists()) {
            file3.createNewFile();
        }
        RandomAccessFile randomAccessFile = new RandomAccessFile(str4, "r");
        long length = randomAccessFile.length() - j;
        if (length < 0) {
            length = 0;
        }
        randomAccessFile.seek(length);
        byte[] bArr = new byte[1024];
        FileOutputStream fileOutputStream = new FileOutputStream(file3);
        while (true) {
            int read = randomAccessFile.read(bArr);
            if (read == -1) {
                break;
            }
            fileOutputStream.write(bArr, 0, read);
        }
        fileOutputStream.flush();
        fileOutputStream.close();
        randomAccessFile.close();
        if (file2.exists()) {
            file2.delete();
        }
    }

    private static long getFileSize(String str) throws Exception {
        File file = new File(str);
        if (file.exists()) {
            FileInputStream fileInputStream = new FileInputStream(file);
            long available = fileInputStream.available();
            fileInputStream.close();
            return available;
        }
        return 0L;
    }

    public static String getDeviceInfo() {
        return String.format("Android version: %s(%s), API: %d\nManufacturer:    %s\nModel:           %s\nProduct:         %s\nID:              %s\nBoard/CPU:       %s/%s\n", Build.VERSION.RELEASE, Build.VERSION.INCREMENTAL, Integer.valueOf(Build.VERSION.SDK_INT), Build.MANUFACTURER, Build.MODEL, Build.PRODUCT, Build.ID, Build.BOARD, Build.CPU_ABI);
    }

    private static void zipFile(ZipOutputStream zipOutputStream, File file, String str) throws IOException {
        File[] listFiles;
        FileInputStream fileInputStream = null;
        try {
            try {
                try {
                } catch (IOException e) {
                    e = e;
                }
                if (file.exists()) {
                    if (!file.isDirectory()) {
                        byte[] bArr = new byte[8192];
                        FileInputStream fileInputStream2 = new FileInputStream(file);
                        try {
                            zipOutputStream.putNextEntry(new ZipEntry(str + file.getName()));
                            while (true) {
                                int read = fileInputStream2.read(bArr);
                                if (read == -1) {
                                    break;
                                }
                                zipOutputStream.write(bArr, 0, read);
                            }
                            zipOutputStream.flush();
                            zipOutputStream.closeEntry();
                            fileInputStream = fileInputStream2;
                        } catch (IOException e2) {
                            e = e2;
                            fileInputStream = fileInputStream2;
                            e.printStackTrace();
                            if (fileInputStream != null) {
                                fileInputStream.close();
                            }
                            return;
                        } catch (Throwable th) {
                            th = th;
                            fileInputStream = fileInputStream2;
                            if (fileInputStream != null) {
                                try {
                                    fileInputStream.close();
                                } catch (IOException e3) {
                                    e3.printStackTrace();
                                }
                            }
                            throw th;
                        }
                    } else {
                        for (File file2 : file.listFiles()) {
                            zipFile(zipOutputStream, file2, str + file.getName() + "/");
                        }
                    }
                    if (fileInputStream != null) {
                        fileInputStream.close();
                    }
                }
            } catch (IOException e4) {
                e4.printStackTrace();
            }
        } catch (Throwable th2) {
            th = th2;
        }
    }

    private static boolean writeLogcat(String str) {
        try {
            File file = new File(str);
            if (file.exists()) {
                file.delete();
            }
            Runtime.getRuntime().exec(new String[]{"logcat", "-d", "-v", "threadtime", "-f", str}).waitFor();
        } catch (Exception e) {
            error(TAG, "writeLogcat failed.", e);
        }
        File file2 = new File(str);
        return file2.exists() && file2.length() > 0;
    }

    private static String logStringFormat(String str, String str2, String str3, StackTraceElement stackTraceElement) {
        mDateFormat.format(new Date());
        String className = stackTraceElement.getClassName();
        return String.format(Locale.CHINA, "[%s:%s:%d] %s", className.substring(className.lastIndexOf(46) + 1), stackTraceElement.getMethodName(), Integer.valueOf(stackTraceElement.getLineNumber()), str3);
    }

    public static String getmCrashLogDir() {
        return mCrashLogDir;
    }

    public static String getProcessName(Context context) {
        int myPid = Process.myPid();
        for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : ((ActivityManager) context.getSystemService("activity")).getRunningAppProcesses()) {
            if (runningAppProcessInfo.pid == myPid) {
                return runningAppProcessInfo.processName;
            }
        }
        return null;
    }

    public static void updateLogLevel(Context context, int i) {
        if (i < 2) {
            i = 2;
        }
        if (i > 7) {
            i = 7;
        }
        mPrintLogLevel = i;
        setLogLevel(i);
        SharedPreferences.Editor edit = context.getSharedPreferences(PREF_SHARED_LOG, 0).edit();
        edit.putInt(PREF_LOG_LEVEL, mPrintLogLevel);
        edit.apply();
    }

    public static void updateWriteLogLevel(Context context, int i) {
        if (i < 2) {
            i = 2;
        }
        if (i > 7) {
            i = 7;
        }
        mWriteLogLevel = i;
        setWriteFileLevel(i);
        SharedPreferences.Editor edit = context.getSharedPreferences(PREF_SHARED_LOG, 0).edit();
        edit.putInt(PREF_WRITE_LOG_LEVEL, mWriteLogLevel);
        edit.apply();
    }

    public static int getWriteLogLevel(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_SHARED_LOG, 0);
        if (sharedPreferences.contains(PREF_WRITE_LOG_LEVEL)) {
            return sharedPreferences.getInt(PREF_WRITE_LOG_LEVEL, 2);
        }
        return 2;
    }

    public static int getLogLevel(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_SHARED_LOG, 0);
        if (sharedPreferences.contains(PREF_LOG_LEVEL)) {
            return sharedPreferences.getInt(PREF_LOG_LEVEL, 4);
        }
        return 4;
    }

    public static String getExceptionContent(Throwable th) {
        if (th == null) {
            return "unknown exception";
        }
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        th.printStackTrace(printWriter);
        printWriter.flush();
        return stringWriter.toString();
    }

    public static String getTimestamp() {
        String format = new SimpleDateFormat("HH:mm:ss.SSS").format(new Date());
        return " Timestamp----" + format;
    }

    public static void error(String str, String str2) {
        safeNativeLog(6, str, logStringFormat(LOG_ERROR_STR, str, str2, new Throwable().getStackTrace()[1]));
    }

    public static void error(String str, String str2, Object... objArr) {
        safeNativeLog(6, str, logStringFormat(LOG_ERROR_STR, str, String.format(str2, objArr), new Throwable().getStackTrace()[1]));
    }

    public static void error(String str, String str2, Throwable th) {
        safeNativeLog(6, str, logStringFormat(LOG_ERROR_STR, str, str2 + getExceptionContent(th), new Throwable().getStackTrace()[1]));
    }

    public static void warn(String str, String str2) {
        safeNativeLog(5, str, logStringFormat(LOG_WARN_STR, str, str2, new Throwable().getStackTrace()[1]));
    }

    public static void warn(String str, String str2, Object... objArr) {
        safeNativeLog(5, str, logStringFormat(LOG_WARN_STR, str, String.format(str2, objArr), new Throwable().getStackTrace()[1]));
    }

    public static void warn(String str, String str2, Throwable th) {
        safeNativeLog(5, str, logStringFormat(LOG_WARN_STR, str, str2 + getExceptionContent(th), new Throwable().getStackTrace()[1]));
    }

    public static void info(String str, String str2) {
        safeNativeLog(4, str, logStringFormat(LOG_INFO_STR, str, str2, new Throwable().getStackTrace()[1]));
    }

    public static void info(String str, String str2, Object... objArr) {
        safeNativeLog(4, str, logStringFormat(LOG_INFO_STR, str, String.format(str2, objArr), new Throwable().getStackTrace()[1]));
    }

    public static void info(String str, String str2, Throwable th) {
        safeNativeLog(4, str, logStringFormat(LOG_INFO_STR, str, str2 + getExceptionContent(th), new Throwable().getStackTrace()[1]));
    }

    public static void debug(String str, String str2) {
        safeNativeLog(3, str, logStringFormat(LOG_DEBUG_STR, str, str2, new Throwable().getStackTrace()[1]));
    }

    public static void debug(String str, String str2, Object... objArr) {
        safeNativeLog(3, str, logStringFormat(LOG_DEBUG_STR, str, String.format(str2, objArr), new Throwable().getStackTrace()[1]));
    }

    public static void debug(String str, String str2, Throwable th) {
        safeNativeLog(3, str, logStringFormat(LOG_DEBUG_STR, str, str2 + getExceptionContent(th), new Throwable().getStackTrace()[1]));
    }

    private static void safeNativeLog(int i, String str, String str2) {
        try {
            nativeLog(i, str, str2);
        } catch (Throwable th) {
            android.util.Log.e(TAG, "can't call native log, maybe library not loaded", th);
        }
    }
}
